import React, { Component } from 'react';
import { BackHandler, Keyboard, NativeModules, SafeAreaView, ScrollView, StyleSheet, Text, View, } from 'react-native';
import user from '@/api/user';
import { AsyncStorage, SyncStorage, cache, msg, SendMsgCode, ValidConst } from '@/common';
import { isAndroid, px2dp, fontColorCoffee } from '@/styles';
import { checkUserAgreement, getAgreementByArray } from '@/common/agreement-version';
import { iconPhone, iconSecurity } from '@/images';
import baseConfig from '@/config/baseConfig';
import HeaderLogo from './components/header-logo';
import XmInput from './components/xm-input';
import OtherWay from './components/other-way';
import LoginBtn from './components/login-btn';
import CheckWay from './components/check-way';
import FirstLoadAPP from './components/first-loadapp';

const { terminalCode } = baseConfig;
const CookieManager = NativeModules.RNCookieManagerIOS;
export default class LoginView extends Component {
  // static navigationOptions = {
  //   header: null,
  // };

  constructor(props) {
    super(props);
    this.navigation = props.navigation;
    this.state = {
      role: '',
      mobile: '',
      code: '',
      password: '',
      keyboardHeight: 0,
      showState: 2,
      isCodeLogin: true,
      isPwdLogin: false,
      user: {},
      onDisappear: true,
      articlesList: [],
      wechatSuccessUserInfo: null,
      systemInfo: {}
    };
    // this.getOperation();
  }

  componentDidMount() {
    this._keyboardDidHide();
    console.log('登录页面加载完成~~');
    this.getUserInfo();
    // 查询隐私协议版本
    getAgreementByArray(
      [{ appCode: terminalCode, code: 'agreement', }, { appCode: terminalCode, code: 'privacyAgreement', }, { appCode: terminalCode, code: 'PerInfoAgreement', }],
      (data) => {
        this.setState({ articlesList: data });
      },
    );
    this.getSystemInfo();
  }

  componentWillUnmount() {
    Keyboard.dismiss();
    // if (Platform.OS === 'android') {
    //   BackHandler.removeEventListener(
    //     'hardwareBackPress',
    //     this.handleBackPress,
    //   );
    // }
  }

  onChangeText = (name, value) => {
    this.setState({ [name]: value });
  };

  onPressLogin = () => {
    // 验证码登录后判断用户有没有设置密码 ，如果没有则跳转到设置密码页面
    const { isCodeLogin, isPwdLogin, articlesList } = this.state;
    if (isCodeLogin) {
      this.basicRegex('msgLogin', (mobile, code) => {
        this.msgLoginMethod(mobile, code, articlesList);
      });
    } else if (isPwdLogin) {
      this.basicRegex('pwdLogin', (mobile, password) => {
        this.pwdLoginMethod(mobile, password, articlesList);
      });
    }
  };

  render() {
    const {
      showState,
      isCodeLogin,
      isPwdLogin,
      mobile,
      code,
      password,
      onDisappear,
      articlesList,
    } = this.state;
    const isActive =
      mobile !== '' &&
      mobile.length === 11 &&
      ((code !== '' && code.length === 4) || password !== '');
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <ScrollView style={{ flex: 1 }}>
          {/* <BackView goBack={this.goBack} /> */}
          <HeaderLogo />
          <View style={{ marginTop: px2dp(50), alignItems: 'center' }}>
            <XmInput
              leftIcon={iconPhone}
              name='mobile'
              placeholder='输入手机号'
              onChange={this.onChangeText}
            />
            {isCodeLogin && (
              <View style={styles.pwdWrap}>
                <XmInput
                  leftIcon={iconSecurity}
                  name='code'
                  placeholder='输入验证码'
                  onChange={this.onChangeText}
                />
                <SendMsgCode
                  frameStyle={styles.sendBtn}
                  activeTextStyle={{ color: fontColorCoffee }}
                  count={60}
                  pressAction={this.sendMsgCode}
                  changeWithCount={(count) => `${count}s后重试`}
                  id='login'
                  ref={(e) => {
                    this.countDownButton = e;
                  }}
                />
              </View>
            )}
            {isPwdLogin && (
              <View style={styles.pwdWrap}>
                <XmInput
                  leftIcon={iconSecurity}
                  name='password'
                  placeholder='输入密码'
                  onChange={this.onChangeText}
                />
                <Text style={styles.forgetPwd} onPress={this.toGetPwd}>
                  忘记密码?
                </Text>
              </View>
            )}
          </View>
          <View style={{ flex: 1, alignItems: 'center' }}>
            <LoginBtn
              btnStyle={{ borderRadius: px2dp(44) }}
              disabled={!isActive}
              isActive={isActive}
              submit={this.onPressLogin}
            />
            <CheckWay
              style={styles.checkWayStyle}
              submit={this.checkLoginWay}
              loginWay={isCodeLogin ? '密码登录' : '验证码登录'}
            />
          </View>
          <View style={{ flex: 1, alignItems: 'center', marginTop: px2dp(60) }}>
            <OtherWay
              showState={showState}
              articlesList={articlesList}
              loginResult={(isSuccess) => {
                if (isSuccess) {
                  this.weChatLoginSuccessMethod();
                }
              }}
            />
          </View>

        </ScrollView>
        {!onDisappear && (
          <FirstLoadAPP
            articlesList={articlesList}
            onDisappear={this.firstLoadDisappear}
          />
        )}
      </SafeAreaView>
    );
  }

   // 获取设备信息
   getSystemInfo = () => {
     NativeModules.BridgeManager.getSystemInfo(systemInfo => {
       console.log('🚀🚀🚀wimi======>>>systemInfo', systemInfo);
       this.setState({ systemInfo });
     });
   }

  getUserInfo = () => {
    user.getUserInfo().then((res) => {
      if (res.success) {
        this.setState({ user: res.data });
      } else {
        msg.emit('app:loginTips', true);
      }
    });
  };

  getOperation() {
    NativeModules.BridgeManager.getAppVersion((v) => {
      if (v) {
        user.getOperation({ type: Platform.OS, versionNum: v }).then((res) => {
          if (res.success && res.data.length > 0) {
            const operationList = res.data;
            for (let i = 0; i < operationList.length; i++) {
              if (operationList[i].code === 'wxdl') {
                this.setState({
                  showState: operationList[i].state,
                });
              }
            }
          } else {
            this.setState({
              showState: 2,
            });
          }
        });
      }
    });
  }

  _keyboardDidShow(e) {
    console.log(e, '键盘高度');
    this.setState({
      keyboardHeight: e.endCoordinates.height,
    });
  }

  _keyboardDidHide() {
    this.setState({
      keyboardHeight: 0,
    });
  }

  // 角色判断，不同角色进入不同app
  goToRoleApp = () => {
    const { role } = this.state;
    if (!role) {
      msg.emit('router: reset', {
        routeName: 'RoleSwitch',
      });
      return;
    }
    // 司机：driver  车主：car_owner  货主：goods_owner
    if (role === 'driver') {
      msg.emit('router: reset', {
        routeName: 'DriverTab',
      });
    } else if (role === 'car_owner') {
      msg.emit('router: reset', {
        routeName: 'CarOwnerTab',
      });
    } else if (role === 'goods_owner') {
      msg.emit('router: reset', {
        routeName: 'GoodsOwnerTab',
      });
    }
  };

  // 处理安卓物理返回键
  // handleBackPress = () => {
  //   return true;
  // };

  firstLoadDisappear = (isAgree) => {
    this.setState({ onDisappear: true });
    if (isAgree) {
      const {
        articlesList,
        wechatSuccessUserInfo,
      } = this.state;
      // 登录逻辑
      if (wechatSuccessUserInfo) {
        // 登录成功
        user.addUserDeal(this.uploadAgreementParams(articlesList)).then(res => {
          if (res.success) {
            AsyncStorage.setItem(cache.USER_INFO, wechatSuccessUserInfo.data);
            // msg.emit('router: reset', {
            //   routeName: 'Tab',
            // });
            this.goToRoleApp();
            this.setState({ wechatSuccessUserInfo: null });
          } else {
            msg.emit('app:tip', { text: res.msg });
          }
        });
      } else {
        this.loginSuccessMethod(articlesList);
      }
    }
  };

  goBack = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    if (routerFrom === 'ChangePhone') {
      // msg.emit('router: reset', {
      //   routeName: 'Tab',
      // });
      this.goToRoleApp();
    } else {
      msg.emit('router: back');
    }
  };

  checkLoginWay = () => {
    const { isCodeLogin, isPwdLogin } = this.state;
    this.setState({
      isCodeLogin: !isCodeLogin,
      isPwdLogin: !isPwdLogin,
      code: '',
      password: '',
    });
  };

  // 发送验证码
  sendMsgCode = () => {
    this.basicRegex('sendMsg', (mobile) => {
      this.countDownButton.startCountDown(() => {
        user.requireSmsCode({ mobile }).then((res) => {
          if (!res.success) {
            NativeModules.WindowModule.showWindow(
              { content: '验证码发送失败', onlyRightBtn: '1' },
              (e) => { },
            );
          }
        });
      });
    });
  };

  toGetPwd = () => {
    const { user } = this.state;
    msg.emit('router: goToNext', {
      routeName: 'InputMobile',
      user,
    });
  };

   // 登录成功
   loginSuccessMethod = (articlesList) => {
     user.addUserDeal(this.uploadAgreementParams(articlesList)).then((res) => {
       if (res.success) {
         this.loginSuccessQueryUserInfo();
       } else {
         msg.emit('app:tip', { text: res.msg });
       }
     });
   };

  // 密码登录
  pwdLoginMethod = (mobile, loginPwd, articlesList) => {
    const { systemInfo } = this.state;
    const { os, sysVersionNum, appVersion } = systemInfo;
    user.loginPwd({ mobile, loginPwd, terminalCode, appVersion, terminalType: os, versionNum: sysVersionNum }).then((loginRes) => {
      if (loginRes.success) {
        // 登录成功，存储tokenid
        AsyncStorage.setItem(cache.TOKEN_ID, JSON.stringify(loginRes.data));
        this.checkUserAgreementIshow(articlesList, mobile);
      } else {
        msg.emit('app:tip', { text: loginRes.msg });
      }
    });
  };

  // 验证码登录
  msgLoginMethod = (mobile, code, articlesList) => {
    const { systemInfo } = this.state;
    const { os, sysVersionNum, appVersion } = systemInfo;
    user
      .smsLogin({ mobile, code, terminalCode, appVersion, terminalType: os, versionNum: sysVersionNum })
      .then((res) => {
        if (res.success) {
          // 登录成功，存储tokenid
          AsyncStorage.setItem(cache.TOKEN_ID, JSON.stringify(res.data));
          this.checkUserAgreementIshow(articlesList, mobile);
        } else {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '温馨提示',
            text: res.msg,
            cancelText: '取消',
            isClickBg: false,
            okFn: () => { },
          });
        }
      });
  };

  checkUserAgreementIshow =(articlesList, mobile) => {
    checkUserAgreement(mobile, articlesList, (isShow) => {
      if (isShow) {
      // 弹窗
        this.setState({ onDisappear: false });
      } else {
        // 登录成功
        this.loginSuccessQueryUserInfo();
      }
    });
  }

  loginSuccessQueryUserInfo =() => {
    user
      .getUserInfo()
      .then(info => {
        if (info.success) {
          if (!isAndroid) {
            // 此处为了兼容ios 杀进程 cookie 失效问题
            CookieManager.getAll().then((res2) => {
              console.log('🚀🚀🚀wimi======>>>res', res2);
              SyncStorage.setItem('XMSESSION', res2);
            });
          }

          AsyncStorage.setItem(cache.USER_INFO, info.data);
          // msg.emit('router: reset', {
          //   routeName: 'Tab',
          // });
          this.goToRoleApp();
        } else {
          msg.emit('app:messageBox', {
            isVisible: true,
            title: '温馨提示',
            text: info.msg,
            cancelText: '取消',
            isClickBg: false,
            okFn: () => { },
          });
        }
      })
      .catch(() => {
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '温馨提示',
          text: '登录用户信息异常，请重新登录',
          cancelText: '取消',
          isClickBg: false,
          okFn: () => { },
        });
      });
  }

  // 获取微信相关数据成功处理逻辑
  weChatLoginSuccessMethod = () => {
    const { articlesList } = this.state;
    user
      .getUserInfo()
      .then((res) => {
        if (res.success) {
          checkUserAgreement(res.data.wholeMobile, articlesList, (isShow) => {
            if (isShow) {
              // 微信弹窗
              this.setState({ onDisappear: false, wechatSuccessUserInfo: res });
            } else {
              // 登录成功
              user
                .addUserDeal(this.uploadAgreementParams(articlesList))
                .then((res1) => {
                  if (res1.success) {
                    if (!isAndroid) {
                      // 此处为了兼容ios 杀进程 cookie 失效问题
                      CookieManager.getAll().then((res2) => {
                        console.log('🚀🚀🚀wimi======>>>res', res2);
                        SyncStorage.setItem('XMSESSION', res2);
                      });
                    }

                    AsyncStorage.setItem(cache.USER_INFO, res.data);
                    // msg.emit('router: reset', {
                    //   routeName: 'Tab',
                    // });
                    this.goToRoleApp();
                  } else {
                    msg.emit('app:tip', { text: res.msg });
                  }
                });
            }
          });
        } else {
          NativeModules.WindowModule.showWindow(
            { content: res.msg, onlyRightBtn: '1' },
            (e) => { },
          );
        }
      })
      .catch((error) => {
        NativeModules.WindowModule.showWindow(
          { content: '登录用户信息异常，请重新登录', onlyRightBtn: '1' },
          (e) => { },
        );
      });
  };

   // 组装隐私上传报文
   uploadAgreementParams = (articlesList) => {
     let params = [];
     articlesList.map((item) => {
       params.push({
         dealCode: item.code,
         dealContent: item.content,
         versionNum: item.versionNum,
         dealTitle: item.title,
         terminalCode
       });
     });
     return params;
   };

  basicRegex = (flag, callback) => {
    const { mobile, code, password, articlesList } = this.state;
    const regex = ValidConst.phone;
    const regexPwd = ValidConst.password;
    if (mobile === '') {
      NativeModules.WindowModule.showWindow(
        {
          content: '请输入手机号',
          onlyRightBtn: '1',
        },
        (e) => { },
      );
      return;
    }
    if (!regex.test(mobile)) {
      NativeModules.WindowModule.showWindow(
        {
          content: '请输入正确的手机号码',
          onlyRightBtn: '1',
        },
        (e) => { },
      );
      return;
    }
    if (flag === 'pwdLogin' && !regexPwd.test(password)) {
      NativeModules.WindowModule.showWindow(
        {
          content: '密码错误',
          onlyRightBtn: '1',
        },
        (e) => { },
      );
      return;
    }
    if (flag === 'sendMsg') {
      callback && callback(mobile);
    } else
    if (flag === 'msgLogin') {
      callback && callback(mobile, code);
    } else if (flag === 'pwdLogin') {
      callback && callback(mobile, password);
    }
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    // //设置次轴的对齐方式
    alignItems: 'center',
    // height: Dimensions.get('window').height - 20,
  },
  pwdWrap: {
    width: '100%',
    marginTop: px2dp(20),
    alignItems: 'center',
    justifyContent: 'center',
  },
  sendBtn: {
    position: 'absolute',
    right: 0,
    borderWidth: 0,
    fontSize: px2dp(28),
    backgroundColor: 'transparent',
  },
  btnCheckWayStyle: {
    justifyContent: 'center',
    alignItems: 'center',
    width: px2dp(640),
    height: 48,
    borderRadius: 8,
    marginTop: 24,
  },
  loginWay: {
    color: '#BA914A',
    fontSize: px2dp(32),
  },
  forgetPwd: {
    position: 'absolute',
    right: px2dp(32),
    borderWidth: 0,
    fontSize: px2dp(28),
    backgroundColor: 'transparent',
    color: '#999896',
  },
  checkWayStyle: {
    borderWidth: px2dp(1),
    borderColor: fontColorCoffee,
    borderRadius: px2dp(44),
    height: px2dp(88),
    marginTop: px2dp(32)
  }
});
